package cn.tedu.service;

import cn.tedu.entity.Order;
import cn.tedu.feign.AccountClient;
import cn.tedu.feign.EasyIdClient;
import cn.tedu.feign.StorageClient;
import cn.tedu.mapper.OrderMapper;
import cn.tedu.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * @author Administrator
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;

    @Transactional  //开启本地事务
    @GlobalTransactional  //开启全局事务
    @Override
    public void create(Order order) {
        // 远程调用ID发号器,获取订单ID
        Long id = Long.valueOf(easyIdClient.nextId("order_business"));
        System.out.println(id);
        order.setId(id);
        orderMapper.create(order);

        //库存和账户没有seata 配置无法启动
//        ?userId=1&productId=1&count=10&money=100
        //远程调用库存,减少库存
        storageClient.decrease(order.getProductId(), order.getCount());
        //远程调用账户,扣减账户
        accountClient.decrease(order.getUserId(), order.getMoney());

    }
}
